/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.core.util

import com.gitee.minimalismstyle.fresh.common.core.domain.Node

/**
 * spring上下文工具对象
 * @author maoxiaodong
 */
object TreeUtils {

    /**
     * 构建树结构
     * @param nodes
     * @return
     */
    fun <T : Node<T, ID>, ID> build(nodes: List<T>): List<T> {
        val trees: MutableList<T> = mutableListOf()
        for (node in nodes) {
            if (node.parentId == null || node.parentId.toString() == "0") {
                trees.add(findChildren(node, nodes))
            }
        }
        return trees
    }

    /**
     * 查找指定节点的子节点
     * @param treeNode 查询的节点
     * @param treeNodes 查询的列表
     * @return
     */
    private fun <T : Node<T, ID>, ID> findChildren(treeNode: T, treeNodes: List<T>): T {
        for (it in treeNodes) {
            if (treeNode.id == it.parentId) {
                if (treeNode.children == null) {
                    treeNode.children = mutableListOf()
                }
                treeNode.children?.add(findChildren(it, treeNodes))
            }
        }
        return treeNode
    }
}